package com.industrial.premu.controller.sqsj;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.controller.BaseController;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.core.web.page.TableDataInfo;
import com.industrial.common.log.annotation.Log;
import com.industrial.common.log.enums.BusinessType;
import com.industrial.common.security.annotation.RequiresPermissions;

import com.industrial.common.security.utils.DictUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.components.strategy.XlsxImportContext;
import com.industrial.premu.domain.*;
import com.industrial.premu.domain.sqsj.*;
import com.industrial.premu.dto.IndexWeightParamsDto;
import com.industrial.premu.dto.PreMuCustomIndicatorDto;
import com.industrial.premu.mapper.PreMuImportDetailInfoMapper;
import com.industrial.premu.mapper.PreMuIndexWeightMainMapper;
import com.industrial.premu.mapper.SysOperErrorMapper;
import com.industrial.premu.service.*;
import com.industrial.premu.vo.PreMuIndexWeightMainVo;
import com.industrial.system.api.domain.SysDictData;
import com.industrial.system.api.domain.SysUser;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 涉企数据导入记录Controller
 *
 * @author SangGuangCan
 * @date 2024-01-24
 */
@RestController
@RequestMapping("/pre_mu_import_log")
public class PreMuImportLogController extends BaseController {
    @Autowired
    private SysOperErrorMapper sysOperErrorMapper;
    @Autowired
    private IPreMuImportLogService preMuImportLogService;

    @Autowired
    private PreMuImportDetailInfoMapper preMuImportDetailInfoMapper;

    @Autowired
    private IPreMuImportHuanbaoService preMuImportHuanbaoService;

    @Autowired
    private IPreMuImportTongjiService preMuImportTongjiService;

    @Autowired
    private PreMuIndexWeightMainMapper preMuIndexWeightMainMapper;

    @Autowired
    private IPreMuCustomIndicatorService preMuCustomIndicatorService;

    @Autowired
    private IPreMuImportGuotuService preMuImportGuotuService;

    @Autowired
    private IPreMuImportRensheService preMuImportRensheService;

    @Autowired
    private IPreMuImportShuiliService preMuImportShuiliService;


    @Autowired
    private IPreMuIndexWeightMainService preMuIndexWeightMainService;

    @Autowired
    private IPreMuImportBenefitEvaluationService preMuImportBenefitEvaluationService;

    @Autowired
    private IPreMuImportBenefitEvaluationNoService preMuImportBenefitEvaluationNoService;

    @Autowired
    private IPreMuAddSubstractItemService preMuAddSubstractItemService;

    @Autowired
    private IPreMuImportAddSubstractService preMuImportAddSubstractService;

    @Autowired
    private IPreMuImportShuiwuService preMuImportShuiwuService;

    @Autowired
    private IPreMuImportVetoService preMuImportVetoService;

    @Autowired
    private IPreMuRejectService preMuRejectService;

    @Autowired
    private IPreMuFileService preMuFileService;

    private Map<String, String> fileMap = new HashMap<>(16);

    @PostConstruct
    public void init() {
//        fileMap.put("规上企业-统计局导入数据模板.xlsx","/Volumes/SGC/temp/muchan/规上企业-统计局导入数据模板.xlsx");
//        fileMap.put("规上企业-生态环境局导入数据模板.xlsx","/Volumes/SGC/temp/muchan/规上企业-生态环境局导入数据模板.xlsx");
//        fileMap.put("规上企业-水利局导入数据模板（试点县区）.xlsx","/Volumes/SGC/temp/muchan/规上企业-水利局导入数据模板（试点县区）.xlsx");
//        fileMap.put("规上企业-税务局导入数据模板.xlsx","/Volumes/SGC/temp/muchan/规上企业-税务局导入数据模板.xlsx");
//        fileMap.put("规上企业-自然资源和规划局导入数据模板.xlsx","/Volumes/SGC/temp/muchan/规上企业-自然资源和规划局导入数据模板.xlsx");
//        fileMap.put("规下企业-税务局导入数据模板.xlsx","/Volumes/SGC/temp/muchan/规下企业-税务局导入数据模板.xlsx");
//        fileMap.put("规下企业-统计局导入数据模板.xlsx","/Volumes/SGC/temp/muchan/规下企业-统计局导入数据模板.xlsx");
//        fileMap.put("规下企业-自然资源和规划局导入数据模板.xlsx","/Volumes/SGC/temp/muchan/规下企业-自然资源和规划局导入数据模板.xlsx");
//        fileMap.put("评价结果导入模板.xlsx","/Volumes/SGC/temp/muchan/评价结果导入模板.xlsx");
//        fileMap.put("不参评企业基础数据导入（规上规下都可用）.xlsx","/Volumes/SGC/temp/muchan/不参评企业基础数据导入（规上规下都可用）.xlsx");
//        fileMap.put("规上企业-人力资源和社会保障局导入数据模板.xlsx","/Volumes/SGC/temp/muchan/规上企业-人力资源和社会保障局导入数据模板.xlsx");

        fileMap.put("规上企业-统计局导入数据模板.xlsx", "/home/premu/muban/规上企业-统计局导入数据模板.xlsx");
        fileMap.put("规上企业-生态环境局导入数据模板.xlsx", "/home/premu/muban/规上企业-生态环境局导入数据模板.xlsx");
        fileMap.put("规上企业-水利局导入数据模板（试点县区）.xlsx", "/home/premu/muban/规上企业-水利局导入数据模板（试点县区）.xlsx");
        fileMap.put("规上企业-税务局导入数据模板.xlsx", "/home/premu/muban/规上企业-税务局导入数据模板.xlsx");
        fileMap.put("规上企业-自然资源和规划局导入数据模板.xlsx", "/home/premu/muban/规上企业-自然资源和规划局导入数据模板.xlsx");
        fileMap.put("规下企业-税务局导入数据模板.xlsx", "/home/premu/muban/规下企业-税务局导入数据模板.xlsx");
        fileMap.put("规下企业-统计局导入数据模板.xlsx", "/home/premu/muban/规下企业-统计局导入数据模板.xlsx");
        fileMap.put("规下企业-自然资源和规划局导入数据模板.xlsx", "/home/premu/muban/规下企业-自然资源和规划局导入数据模板.xlsx");
        fileMap.put("评价结果导入模板.xlsx", "/home/premu/muban/评价结果导入模板.xlsx");
        fileMap.put("不参评企业基础数据导入（规上规下都可用）.xlsx", "/home/premu/muban/不参评企业基础数据导入（规上规下都可用）.xlsx");
        fileMap.put("规上企业-人力资源和社会保障局导入数据模板.xlsx", "/home/premu/muban/规上企业-人力资源和社会保障局导入数据模板.xlsx");
    }

    /**
     * 查询涉企数据导入记录列表
     */
    @RequiresPermissions("operation:pre_mu_import_log:list")
    @GetMapping("/list")
    public TableDataInfo list(PreMuImportLog preMuImportLog) {
        startPage();
        List<PreMuImportLog> list = preMuImportLogService.selectPreMuImportLogList(preMuImportLog);
        return getDataTable(list);
    }

    /**
     * 导出涉企数据导入记录列表
     */
    @RequiresPermissions("operation:pre_mu_import_log:export")
    @Log(title = "涉企数据导入记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PreMuImportLog preMuImportLog) {
        List<PreMuImportLog> list = preMuImportLogService.selectPreMuImportLogList(preMuImportLog);
        ExcelUtil<PreMuImportLog> util = new ExcelUtil<PreMuImportLog>(PreMuImportLog.class);
        util.exportExcel(response, list, "涉企数据导入记录数据");
    }

    /**
     * 获取涉企数据导入记录详细信息
     */
    @RequiresPermissions("operation:pre_mu_import_log:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(preMuImportLogService.selectPreMuImportLogById(id));
    }

    /**
     * 新增涉企数据导入记录
     */
    @RequiresPermissions("operation:pre_mu_import_log:add")
    @Log(title = "涉企数据导入记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PreMuImportLog preMuImportLog) {
        return toAjax(preMuImportLogService.insertPreMuImportLog(preMuImportLog));
    }

    /**
     * 修改涉企数据导入记录
     */
    @RequiresPermissions("operation:pre_mu_import_log:edit")
    @Log(title = "涉企数据导入记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PreMuImportLog preMuImportLog) {
        return toAjax(preMuImportLogService.updatePreMuImportLog(preMuImportLog));
    }

    /**
     * 删除涉企数据导入记录
     */
    @RequiresPermissions("operation:pre_mu_import_log:remove")
    @Log(title = "涉企数据导入记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(preMuImportLogService.deletePreMuImportLogByIds(ids));
    }

    /**
     * <p>
     * 涉企数据查看详情
     * </p>
     *
     * @param params
     * @return
     */
    @GetMapping("/listInfoData")
    @RequiresPermissions("operation:pre_mu_import_log:listInfoData")
    public TableDataInfo listInfoData(@RequestParam Map<String, String> params) {
        String deptCode = null, year = null;
        if (StringUtils.isBlank(deptCode = params.get("deptCode")) || StringUtils.isBlank(year = params.get("year"))) {
            throw new RuntimeException("没有找到部门代码、年度");
        }
        String companyName = params.get("companyName");
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        startPage();
        //规上企业统计局
        if (StringUtils.equals(deptCode, "01")) {
            PreMuImportTongji queryParams = new PreMuImportTongji();
            queryParams.setYear(year);
            queryParams.setCompanyType("1");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportTongji> preMuImportTongjis = preMuImportTongjiService.selectPreMuImportTongjiList(queryParams);
            return getDataTable(preMuImportTongjis);
        } else if (StringUtils.equals(deptCode, "02")) {
            //规上生态环境局
            PreMuImportHuanbao queryParams = new PreMuImportHuanbao();
            queryParams.setYear(year);
            queryParams.setCompanyType("1");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportHuanbao> preMuImportHuanbaos = preMuImportHuanbaoService.selectPreMuImportHuanbaoList(queryParams);
            return getDataTable(preMuImportHuanbaos);
        } else if (StringUtils.equals(deptCode, "03")) {
            //规上生态环境局
            PreMuImportGuotu queryParams = new PreMuImportGuotu();
            queryParams.setYear(year);
            queryParams.setCompanyType("1");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportGuotu> preMuImportGuotus = preMuImportGuotuService.selectPreMuImportGuotuList(queryParams);
            return getDataTable(preMuImportGuotus);
        } else if (StringUtils.equals(deptCode, "04")) {
            //规上税务局
            PreMuImportShuiwu queryParams = new PreMuImportShuiwu();
            queryParams.setYear(year);
            queryParams.setCompanyType("1");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportShuiwu> preMuImportGuotus = preMuImportShuiwuService.selectPreMuImportShuiwuList(queryParams);
            return getDataTable(preMuImportGuotus);
        } else if (StringUtils.equals(deptCode, "05")) {
            //规上人力资源和社会保障局
            PreMuImportRenshe queryParams = new PreMuImportRenshe();
            queryParams.setYear(year);
            queryParams.setCompanyType("1");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportRenshe> preMuImportRenshes = preMuImportRensheService.selectPreMuImportRensheList(queryParams);
            return getDataTable(preMuImportRenshes);
        } else if ("waterBureau".equals(deptCode)) {
            PreMuImportShuili queryParams = new PreMuImportShuili();
            queryParams.setYear(year);
            queryParams.setCompanyType("1");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportShuili> preMuImportShuilis = preMuImportShuiliService.selectPreMuImportShuiliList(queryParams);
            return getDataTable(preMuImportShuilis);
        } else if ("evaluationUpper".equals(deptCode)) {
            //规上企业-评价结果(仅导入结果时使用)
            PreMuImportBenefitEvaluation queryParams = new PreMuImportBenefitEvaluation();
            queryParams.setYear(year);
            queryParams.setCompanyType("1");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportBenefitEvaluation> preMuImportBenefitEvaluations = preMuImportBenefitEvaluationService.selectPreMuImportBenefitEvaluationList(queryParams);
            return getDataTable(preMuImportBenefitEvaluations);
        } else if ("06".equals(deptCode)) {
            //规下企业统计局
            PreMuImportTongji queryParams = new PreMuImportTongji();
            queryParams.setYear(year);
            queryParams.setCompanyType("2");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportTongji> preMuImportTongjis = preMuImportTongjiService.selectPreMuImportTongjiList(queryParams);
            return getDataTable(preMuImportTongjis);
        } else if ("07".equals(deptCode)) {
            //规下企业-自然资源和规划局
            PreMuImportGuotu queryParams = new PreMuImportGuotu();
            queryParams.setYear(year);
            queryParams.setCompanyType("2");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportGuotu> preMuImportGuotus = preMuImportGuotuService.selectPreMuImportGuotuList(queryParams);
            return getDataTable(preMuImportGuotus);
        } else if ("09".equals(deptCode)) {
            //规下企业-税务局
            PreMuImportShuiwu queryParams = new PreMuImportShuiwu();
            queryParams.setYear(year);
            queryParams.setCompanyType("2");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportShuiwu> preMuImportGuotus = preMuImportShuiwuService.selectPreMuImportShuiwuList(queryParams);
            return getDataTable(preMuImportGuotus);
        } else if ("evaluationlower".equals(deptCode)) {
            //规下企业-评价结果(仅导入结果时使用)
            PreMuImportBenefitEvaluation queryParams = new PreMuImportBenefitEvaluation();
            queryParams.setYear(year);
            queryParams.setCompanyType("2");
            queryParams.setCounty(sysUser.getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportBenefitEvaluation> preMuImportBenefitEvaluations = preMuImportBenefitEvaluationService.selectPreMuImportBenefitEvaluationList(queryParams);
            return getDataTable(preMuImportBenefitEvaluations);
        } else if ("addupper".equals(deptCode)) {
            //规上企业-加分项查询
            PreMuImportAddSubstract queryPram = new PreMuImportAddSubstract();
            queryPram.setYear(year);
            queryPram.setCompanyType("1");
            queryPram.setItemType(1L);
            queryPram.setCounty(sysUser.getDistrict());
            queryPram.setCompanyName(companyName);
            List<PreMuImportAddSubstract> preMuImportAddSubstracts = preMuImportAddSubstractService.selectPreMuImportAddSubstractList(queryPram);
            return getDataTable(preMuImportAddSubstracts);
        } else if ("addlower".equals(deptCode)) {
            //规下企业-加分项查询
            PreMuImportAddSubstract queryPram = new PreMuImportAddSubstract();
            queryPram.setYear(year);
            queryPram.setCompanyType("2");
            queryPram.setItemType(1L);
            queryPram.setCounty(sysUser.getDistrict());
            queryPram.setCompanyName(companyName);
            List<PreMuImportAddSubstract> preMuImportAddSubstracts = preMuImportAddSubstractService.selectPreMuImportAddSubstractList(queryPram);
            return getDataTable(preMuImportAddSubstracts);
        } else if ("substractupper".equals(deptCode)) {
            //规上企业-减分项查询
            PreMuImportAddSubstract queryPram = new PreMuImportAddSubstract();
            queryPram.setYear(year);
            queryPram.setCompanyType("1");
            queryPram.setItemType(2L);
            queryPram.setCounty(sysUser.getDistrict());
            queryPram.setCompanyName(companyName);
            List<PreMuImportAddSubstract> preMuImportAddSubstracts = preMuImportAddSubstractService.selectPreMuImportAddSubstractList(queryPram);
            return getDataTable(preMuImportAddSubstracts);
        } else if ("substraclower".equals(deptCode)) {
            //规下企业-减分项导入数据模版
            PreMuImportAddSubstract queryPram = new PreMuImportAddSubstract();
            queryPram.setYear(year);
            queryPram.setCompanyType("2");
            queryPram.setItemType(2L);
            queryPram.setCounty(sysUser.getDistrict());
            queryPram.setCompanyName(companyName);
            List<PreMuImportAddSubstract> preMuImportAddSubstracts = preMuImportAddSubstractService.selectPreMuImportAddSubstractList(queryPram);
            return getDataTable(preMuImportAddSubstracts);
        } else if ("notContestant".equals(deptCode) || "notContestant_down".equals(deptCode)) {
            if ("notContestant_down".equals(deptCode)) {
                //不参评企业数据导入
                PreMuImportBenefitEvaluationNo queryParams = new PreMuImportBenefitEvaluationNo();
                queryParams.setCompanyType("2");
                queryParams.setYear(Long.valueOf(year));
                queryParams.setCounty(sysUser.getDistrict());
                queryParams.setCompanyName(companyName);
                List<PreMuImportBenefitEvaluationNo> preMuImportBenefitEvaluationNos = preMuImportBenefitEvaluationNoService.selectPreMuImportBenefitEvaluationNoList(queryParams);
                return getDataTable(preMuImportBenefitEvaluationNos);
            } else {
                PreMuImportBenefitEvaluationNo queryParams = new PreMuImportBenefitEvaluationNo();
                queryParams.setCompanyType("1");
                queryParams.setYear(Long.valueOf(year));
                queryParams.setCounty(sysUser.getDistrict());
                queryParams.setCompanyName(companyName);
                List<PreMuImportBenefitEvaluationNo> preMuImportBenefitEvaluations = preMuImportBenefitEvaluationNoService.selectPreMuImportBenefitEvaluationNoList(queryParams);
                return getDataTable(preMuImportBenefitEvaluations);
            }
        } else if ("vetoupper".equals(deptCode)) {
            //规上企业否决项
            PreMuImportVeto queryParams = new PreMuImportVeto();
            queryParams.setCompanyType("1");
            queryParams.setYear(year);
            queryParams.setDelFlag("0");
            queryParams.setCompanyName(companyName);
            queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
            List<PreMuImportVeto> preMuImportVetos = preMuImportVetoService.selectPreMuImportVetoList(queryParams);
            return getDataTable(preMuImportVetos);
        } else if ("vetolower".equals(deptCode)) {
            //规下企业否决项
            PreMuImportVeto queryParams = new PreMuImportVeto();
            queryParams.setCompanyType("2");
            queryParams.setYear(year);
            queryParams.setDelFlag("0");
            queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportVeto> preMuImportVetos = preMuImportVetoService.selectPreMuImportVetoList(queryParams);
            return getDataTable(preMuImportVetos);
        } else if ("custom".equals(deptCode)) {
            //规上企业自定义
            PreMuCustomIndicatorDto queryParams = new PreMuCustomIndicatorDto();
            queryParams.setCompanyType("1");
            queryParams.setYear(year);
            queryParams.setDelFlag("0");
            queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportCustomIndexLj> preMuImportCustomIndexLjs = preMuCustomIndicatorService.selectImportList(queryParams);
            return getDataTable(preMuImportCustomIndexLjs);
        } else if ("08".equals(deptCode)) {
            //规上企业自定义
            PreMuCustomIndicatorDto queryParams = new PreMuCustomIndicatorDto();
            queryParams.setCompanyType("2");
            queryParams.setYear(year);
            queryParams.setDelFlag("0");
            queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
            queryParams.setCompanyName(companyName);
            List<PreMuImportCustomIndexLj> preMuImportCustomIndexLjs = preMuCustomIndicatorService.selectImportList(queryParams);
            return getDataTable(preMuImportCustomIndexLjs);
        }

        throw new RuntimeException("没有找到部门名称");
    }

    private final XlsxImportContext xlsxImportContext = new XlsxImportContext();

    /***
     * 重新优化导入涉企数据的功能
     * @param params 传入的参数
     * @param file 传入的文件
     * @param request 请求
     * @return 结果
     */
    @PostMapping("/importExcelDataNew")
    public AjaxResult importExcelDataNew(@RequestParam Map<String, String> params,
                                         @RequestPart("file") MultipartFile file,
                                         HttpServletRequest request){
        String deptCode = null, year = null, companyType = null;
        if (StringUtils.isBlank(deptCode = params.get("deptCode"))
                || StringUtils.isBlank(year = params.get("year"))
                || StringUtils.isBlank(companyType = params.get("companyType"))) {
            return AjaxResult.warn("请选择需要导入的部门、年份、企业类型");
        }

        try{
            xlsxImportContext.importXlsx(deptCode,file,year,companyType);
        }catch (Exception e){
            return AjaxResult.error();
        }

        return AjaxResult.success();
    }

    /**
     * <p>
     * 导入涉企数据
     * </p>
     *
     * @param params
     * @param file
     * @return
     */
    @PostMapping("/importExcelData")
    @RequiresPermissions("operation:pre_mu_import_log:importexcel")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importExcelData(@RequestParam Map<String, String> params, @RequestPart("file") MultipartFile file, HttpServletRequest request) {

        String deptCode = null, year = null, companyType = null;
        if (StringUtils.isBlank(deptCode = params.get("deptCode"))
                || StringUtils.isBlank(year = params.get("year"))
                || StringUtils.isBlank(companyType = params.get("companyType"))) {
            return AjaxResult.warn("请选择需要导入的部门、年份、企业类型");
        }

        AjaxResult result = null;
        try {
            //规上企业统计局
            if (StringUtils.equals(deptCode, "01")) {
                result = preMuImportTongjiService.importTongJiExcelData(year, companyType, file);
            } else if (StringUtils.equals(deptCode, "02")) {
                //规上企业生态环境局
                result = preMuImportHuanbaoService.importHuanbaoExcelData(year, companyType, file);
            } else if (StringUtils.equals(deptCode, "03")) {
                //规上企业自然资源和规划局
                result = preMuImportGuotuService.importGuotuExcelData(year, companyType, file);
            } else if (StringUtils.equals(deptCode, "04")) {
                //规上企业税务局
                result = preMuImportShuiwuService.importShuiWuExcelData(year, companyType, file);
            } else if (StringUtils.equals(deptCode, "05")) {
                //规上企业人力资源和社会保障局
                result = preMuImportRensheService.importRenSheExcelData(year, companyType, file);
            } else if ("waterBureau".equals(deptCode)) {
                //规上企业-水利局(试点县区)
                result = preMuImportShuiliService.importShuiliExcelData(year, companyType, file);
            } else if ("evaluationUpper".equals(deptCode)) {
                //规上企业-评价结果(仅导入结果时使用)
                result = preMuImportBenefitEvaluationService.importEvaluationUpperExcelData(year, companyType, file);
            } else if ("06".equals(deptCode)) {
                //规下企业-统计局
                result = preMuImportTongjiService.importTongJiExcelData(year, companyType, file);
            } else if ("07".equals(deptCode)) {
                //规下企业-自然资源和规划局
                result = preMuImportGuotuService.importGuotuExcelData(year, companyType, file);
            } else if ("09".equals(deptCode)) {
                //规下企业-税务局
                result = preMuImportShuiwuService.importShuiWuExcelData(year, companyType, file);
            } else if ("evaluationlower".equals(deptCode)) {
                //规下企业-评价结果(仅导入结果时使用)
                result = preMuImportBenefitEvaluationService.importEvaluationUpperExcelData(year, companyType, file);
            } else if ("notContestant".equals(deptCode) || "notContestant_down".equals(deptCode)) {
                //不参评企业数据导入
                result = preMuImportBenefitEvaluationNoService.importBenefitEvaluationNoExcelData(year, companyType, file);
            } else if ("addupper".equals(deptCode)) {
                //规上企业加分项导入模版
                result = preMuAddSubstractItemService.importAddSubstractItemExcelData(year, "1", file.getInputStream(), "1");
            } else if ("addlower".equals(deptCode)) {
                //规下企业加分项导入模版
                result = preMuAddSubstractItemService.importAddSubstractItemExcelData(year, "2", file.getInputStream(), "1");
            } else if ("substractupper".equals(deptCode)) {
                //规上企业减分项导入模版
                result = preMuAddSubstractItemService.importAddSubstractItemExcelData(year, "1", file.getInputStream(), "2");
            } else if ("substraclower".equals(deptCode)) {
                //规下企业减分项导入模版
                result = preMuAddSubstractItemService.importAddSubstractItemExcelData(year, "2", file.getInputStream(), "2");
            } else if ("vetoupper".equals(deptCode)) {
                result = preMuImportVetoService.importRejectData(year, "1", file.getInputStream());
            } else if ("vetolower".equals(deptCode)) {
                result = preMuImportVetoService.importRejectData(year, "2", file.getInputStream());
            } else if ("custom".equals(deptCode)) {
                //规上企业自定义指标
                PreMuCustomIndicator queryParams = new PreMuCustomIndicator();
                queryParams.setCompanyType("1");
                queryParams.setYear(year);
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                Optional<BigDecimal> sumScoreOp = Optional.ofNullable(preMuCustomIndicatorService.getSumScoreByCountyAndCompanyType(queryParams));
                BigDecimal sumScore = sumScoreOp.orElse(new BigDecimal(0));
//
//                PreMuIndexWeightMain quearIndexWeightParams = new PreMuIndexWeightMain();
//                quearIndexWeightParams.setYear(year);
//                quearIndexWeightParams.setCompanyType("1");
//                quearIndexWeightParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
//                PreMuIndexWeightMain preMuIndexWeightMain = preMuIndexWeightMainService.selectOne(quearIndexWeightParams);
//                if (preMuIndexWeightMain == null) {
//                    return AjaxResult.warn("没有找到设置的自定义指标");
//                }
//                List<PreMuIndexWeightSub> preMuIndexWeightSubList = preMuIndexWeightMain.getPreMuIndexWeightSubList();
//                if (preMuIndexWeightSubList != null && !preMuIndexWeightSubList.isEmpty()) {
//                    preMuIndexWeightSubList = preMuIndexWeightSubList.stream().filter(k -> StringUtils.equals("自定义指标", k.getIndexName())).collect(Collectors.toList());
//                }
//                BigDecimal p = new BigDecimal("0");
//                for (PreMuIndexWeightSub item : preMuIndexWeightSubList) {
//                    p = p.add(new BigDecimal(item.getIndexValue()));
//                }
                IndexWeightParamsDto indexWeightParams =new IndexWeightParamsDto();
                indexWeightParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                indexWeightParams.setCompanyType("1");
                indexWeightParams.setYear(year);
                indexWeightParams.setIndexName("自定义指标");
                List<PreMuIndexWeightMainVo> weightList=  preMuIndexWeightMainService.weightList(indexWeightParams);
                BigDecimal p = new BigDecimal("0");
                if(!CollectionUtils.isEmpty(weightList)){
                    p = new BigDecimal(weightList.get(0).getIndexValue());
                }
                if (sumScore.compareTo(p) != 0) {

                    Map<String, String> resultMap = new HashMap<>();
                    resultMap.put("msg", "导入成功");
                    resultMap.put("allMsg", "规上自定义指标分值之和 与 指标设置 的自定义指标分值不匹配");

                    return AjaxResult.success(resultMap);
                }
                result = preMuCustomIndicatorService.importData(year, "1", file.getInputStream());
            } else if ("08".equals(deptCode)) {
                //规上企业自定义指标
                PreMuCustomIndicator queryParams = new PreMuCustomIndicator();
                queryParams.setCompanyType("2");
                queryParams.setYear(year);
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                Optional<BigDecimal> sumScoreOp = Optional.ofNullable(preMuCustomIndicatorService.getSumScoreByCountyAndCompanyType(queryParams));
                BigDecimal sumScore = sumScoreOp.orElse(new BigDecimal(0));

//                PreMuIndexWeightMain quearIndexWeightParams = new PreMuIndexWeightMain();
//                quearIndexWeightParams.setYear(year);
//                quearIndexWeightParams.setCompanyType("2");
//                quearIndexWeightParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
//                PreMuIndexWeightMain preMuIndexWeightMain = preMuIndexWeightMainService.selectOne(quearIndexWeightParams);
//                if (preMuIndexWeightMain == null) {
//                    return AjaxResult.warn("没有找到设置的自定义指标");
//                }
//                List<PreMuIndexWeightSub> preMuIndexWeightSubList = preMuIndexWeightMain.getPreMuIndexWeightSubList();
//                BigDecimal p = new BigDecimal("0");
//                for (PreMuIndexWeightSub item : preMuIndexWeightSubList) {
//                    p = p.add(new BigDecimal(item.getIndexValue()));
//                }
                IndexWeightParamsDto indexWeightParams =new IndexWeightParamsDto();
                indexWeightParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                indexWeightParams.setCompanyType("2");
                indexWeightParams.setYear(year);
                indexWeightParams.setIndexName("自定义指标");
                List<PreMuIndexWeightMainVo> weightList=  preMuIndexWeightMainService.weightList(indexWeightParams);
                BigDecimal p = new BigDecimal("0");
                if(!CollectionUtils.isEmpty(weightList)){
                    p = new BigDecimal(weightList.get(0).getIndexValue());
                }
                if (sumScore.compareTo(p) != 0) {
                    Map<String, String> resultMap = new HashMap<>();
                    resultMap.put("msg", "导入成功");
                    resultMap.put("allMsg", "规下自定义指标分值之和 与 指标设置 的自定义指标分值不匹配");

                    return AjaxResult.success(resultMap);
                }
                result = preMuCustomIndicatorService.importData(year, "2", file.getInputStream());
            }

            if (result.isSuccess()) {
                SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
                Map data = (Map) result.get("data");
                PreMuImportLog preMuImportLog = new PreMuImportLog();
                preMuImportLog.setYear(year);
                preMuImportLog.setProvince(sysUser.getProvince());
                preMuImportLog.setCity(sysUser.getCity());
                preMuImportLog.setCounty(sysUser.getDistrict());
                preMuImportLog.setDeptCode(deptCode);

                PreMuImportLog preMuImportLog1 = new PreMuImportLog();
                preMuImportLog1.setCity(sysUser.getCity());
                preMuImportLog1.setCounty(sysUser.getDistrict());
                preMuImportLog1.setDeptCode(deptCode);
                preMuImportLog1.setYear(year);
                String sum = (String) data.get("sum");
                String updateNum = (String) data.get("updateNum");
                List<PreMuImportLog> preMuImportLogs = preMuImportLogService.selectPreMuImportLogList(preMuImportLog1);
                if (preMuImportLogs.size() > 0) {
                    PreMuImportLog preMuImportLog2 = preMuImportLogs.get(0);
                    preMuImportLog.setDeptCodeSum(preMuImportLog2.getDeptCodeSum()+Long.valueOf(sum)-Long.valueOf(updateNum));
                    preMuImportLog.setId(preMuImportLog2.getId());
                    preMuImportLog.setUploadDate(DateUtils.getNowDate());
                    preMuImportLogService.updatePreMuImportLog(preMuImportLog);
                } else {
                    preMuImportLog.setDeptCodeSum(Long.valueOf(sum));
                    preMuImportLog.setId(IdUtil.simpleUUID());
                    preMuImportLog.setUploadDate(DateUtils.getNowDate());
                    preMuImportLogService.insertPreMuImportLog(preMuImportLog);
                }

                Set<String> deptSet = new HashSet<>();
                deptSet.add("01");
                deptSet.add("06");
                deptSet.add("02");
                deptSet.add("03");
                deptSet.add("07");
                deptSet.add("04");
                deptSet.add("09");
                deptSet.add("05");
                deptSet.add("waterBureau");
                if (ArrayUtil.containsAny(deptSet.toArray(), deptCode)) {
                    //修改分析表数据
                    String deptCodeStr = "";
                    //统计局
                    if (StringUtils.equals(deptCode, "01") || StringUtils.equals(deptCode, "06")) {
                        deptCodeStr = "tongjiju";
                    } else if (StringUtils.equals(deptCode, "02")) {
                        //规上生态环境局
                        deptCodeStr = "huanbaoju";
                    } else if (StringUtils.equals(deptCode, "03") || StringUtils.equals(deptCode, "07")) {
                        //自然资源和规划局
                        deptCodeStr = "guotuju";
                    } else if (StringUtils.equals(deptCode, "04") || StringUtils.equals(deptCode, "09")) {
                        //税务局
                        deptCodeStr = "shuiwuju";
                    } else if (StringUtils.equals(deptCode, "05")) {
                        //人社
                        deptCodeStr = "rensheju";
                    } else if (StringUtils.equals(deptCode, "waterBureau")) {
                        //水利
                        deptCodeStr = "shuiliju";
                    }


                    String successSum = (String) data.get("sum");
                    String failureNum = (String) data.get("failureNum");

                    int successNumInt = StringUtils.isNotBlank(successSum) ? Integer.valueOf(successSum) : 0;
                    int failureNumInt = StringUtils.isNotBlank(failureNum) ? Integer.valueOf(failureNum) : 0;

                    PreMuImportDetailInfo quParams = new PreMuImportDetailInfo();
                    quParams.setYears(year);
                    quParams.setDpetCode(deptCodeStr);
                    quParams.setCounty(sysUser.getDistrict());
                    PreMuImportDetailInfo resultImportDetail = preMuImportDetailInfoMapper.selectImportDetail(quParams);
                    if (resultImportDetail != null) {
                        resultImportDetail.setSuccessCount(String.valueOf(successNumInt));
                        resultImportDetail.setFailCount(String.valueOf(failureNumInt));

                        if (failureNumInt > 0) {
                            resultImportDetail.setStatus("部分导入");
                        } else if (successNumInt > 0) {
                            resultImportDetail.setStatus("全部导入");
                        } else {
                            resultImportDetail.setStatus("未导入");
                        }

                        preMuImportDetailInfoMapper.updatePreMuImportDetailInfo(resultImportDetail);
                    } else {
                        resultImportDetail = new PreMuImportDetailInfo();
                        resultImportDetail.setYears(year);
                        resultImportDetail.setBaseId(IdUtil.simpleUUID());
                        resultImportDetail.setCjTime(DateUtils.getNowDate());
                        resultImportDetail.setSuccessCount(String.valueOf(successNumInt));
                        resultImportDetail.setFailCount(String.valueOf(failureNumInt));

                        if (failureNumInt > 0) {
                            resultImportDetail.setStatus("部分导入");
                        } else if (successNumInt > 0) {
                            resultImportDetail.setStatus("全部导入");
                        } else {
                            resultImportDetail.setStatus("未导入");
                        }

                        resultImportDetail.setDpetCode(deptCodeStr);
                        resultImportDetail.setSource("数据导入");
                        resultImportDetail.setProvince(sysUser.getProvince());
                        resultImportDetail.setCity(sysUser.getCity());
                        resultImportDetail.setCounty(sysUser.getDistrict());
                        preMuImportDetailInfoMapper.insertPreMuImportDetailInfo(resultImportDetail);
                    }
                }
            } else {
                return result;
            }
        } catch (Exception e) {
            String requestURI = request.getRequestURI();
            SysOperError sysOperError = new SysOperError();
            sysOperError.setBaseId(IdUtil.simpleUUID());
            sysOperError.setBaseCreateTime(new Date());
            sysOperError.setErrorMsg(e.getMessage());
            sysOperError.setUrlAddress(requestURI);
            sysOperError.setOperId(SecurityUtils.getUserId());
            sysOperErrorMapper.saveErrorInfo(sysOperError);
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("allMsg", "导入失败");
            return AjaxResult.success(resultMap);
        }
        return result;
    }


    @PostMapping("/removeData")
    @RequiresPermissions("operation:pre_mu_import_log:removedata")
    public AjaxResult removeData(String year, String deptCode, HttpServletRequest request) throws Exception {
        try {
            //规上企业统计局
            if ("01".equals(deptCode)) {
                PreMuImportTongji params = new PreMuImportTongji();
                params.setYear(year);
                params.setCompanyType("1");
                params.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportTongjiService.removeData(params, deptCode);
            } else if ("02".equals(deptCode)) {
                //规上环保
                PreMuImportHuanbao params = new PreMuImportHuanbao();
                params.setCompanyType("1");
                params.setYear(year);
                params.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportHuanbaoService.removeData(params, deptCode);
            } else if ("03".equals(deptCode)) {
                //规上企业-自然资源和规划局
                PreMuImportGuotu params = new PreMuImportGuotu();
                params.setCompanyType("1");
                params.setYear(year);
                params.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportGuotuService.removeData(params, deptCode);
            } else if ("04".equals(deptCode)) {
                PreMuImportShuiwu params = new PreMuImportShuiwu();
                params.setCompanyType("1");
                params.setYear(year);
                params.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportShuiwuService.removeData(params, deptCode);
            } else if ("05".equals(deptCode)) {
                PreMuImportRenshe params = new PreMuImportRenshe();
                params.setCompanyType("1");
                params.setYear(year);
                params.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportRensheService.removeData(params, deptCode);
            } else if ("evaluationUpper".equals(deptCode)) {
                PreMuImportBenefitEvaluation params = new PreMuImportBenefitEvaluation();
                params.setCompanyType("1");
                params.setYear(year);
                params.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportBenefitEvaluationService.removeData(params, deptCode);
            } else if ("notContestant".equals(deptCode)) {
                PreMuImportBenefitEvaluationNo params = new PreMuImportBenefitEvaluationNo();
                params.setCompanyType("1");
                params.setYear(Long.valueOf(year));
                params.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportBenefitEvaluationNoService.removeData(params, deptCode);
            } else if ("notContestant_down".equals(deptCode)) {
                PreMuImportBenefitEvaluationNo params = new PreMuImportBenefitEvaluationNo();
                params.setCompanyType("2");
                params.setYear(Long.valueOf(year));
                params.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportBenefitEvaluationNoService.removeData(params, deptCode);
            } else if ("06".equals(deptCode)) {
                //规下企业-统计局
                PreMuImportTongji params = new PreMuImportTongji();
                params.setYear(year);
                params.setCompanyType("2");
                params.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportTongjiService.removeData(params, deptCode);
            } else if ("07".equals(deptCode)) {
                //规下企业-自然资源和规划局
                PreMuImportGuotu queryParams = new PreMuImportGuotu();
                queryParams.setYear(year);
                queryParams.setCompanyType("2");
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportGuotuService.removeData(queryParams, deptCode);
            } else if ("09".equals(deptCode)) {
                //规下企业-税务局
                PreMuImportShuiwu queryParams = new PreMuImportShuiwu();
                queryParams.setYear(year);
                queryParams.setCompanyType("2");
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportShuiwuService.removeData(queryParams, deptCode);
            } else if ("evaluationlower".equals(deptCode)) {
                //规下企业-评价结果(仅导入结果时使用)
                PreMuImportBenefitEvaluation queryParams = new PreMuImportBenefitEvaluation();
                queryParams.setYear(year);
                queryParams.setCompanyType("2");
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportBenefitEvaluationService.removeData(queryParams, deptCode);
            } else if ("addupper".equals(deptCode)) {
                //规上企业加分项
                PreMuImportAddSubstract queryParams = new PreMuImportAddSubstract();
                queryParams.setCompanyType("1");
                queryParams.setItemType(1L);
                queryParams.setYear(year);
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportAddSubstractService.removeData(queryParams, deptCode);
            } else if ("addlower".equals(deptCode)) {
                //规上企业加分项
                PreMuImportAddSubstract queryParams = new PreMuImportAddSubstract();
                queryParams.setCompanyType("2");
                queryParams.setItemType(1L);
                queryParams.setYear(year);
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportAddSubstractService.removeData(queryParams, deptCode);
            } else if ("substractupper".equals(deptCode)) {
                //规上企业减分项
                PreMuImportAddSubstract queryParams = new PreMuImportAddSubstract();
                queryParams.setCompanyType("1");
                queryParams.setItemType(2L);
                queryParams.setYear(year);
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportAddSubstractService.removeData(queryParams, deptCode);
            } else if ("substraclower".equals(deptCode)) {
                //规上企业加分项
                PreMuImportAddSubstract queryParams = new PreMuImportAddSubstract();
                queryParams.setCompanyType("2");
                queryParams.setItemType(2L);
                queryParams.setYear(year);
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportAddSubstractService.removeData(queryParams, deptCode);
            } else if ("vetoupper".equals(deptCode)) {
                //规上企业否决项
                PreMuImportVeto preMuImportVeto = new PreMuImportVeto();
                preMuImportVeto.setCompanyType("1");
                preMuImportVeto.setYear(year);
                preMuImportVeto.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportVetoService.removeData(preMuImportVeto, deptCode);
            } else if ("vetolower".equals(deptCode)) {
                //规上企业否决项
                PreMuImportVeto preMuImportVeto = new PreMuImportVeto();
                preMuImportVeto.setCompanyType("2");
                preMuImportVeto.setYear(year);
                preMuImportVeto.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportVetoService.removeData(preMuImportVeto, deptCode);
            } else if ("custom".equals(deptCode)) {
                //规上企业自定义指标
                PreMuCustomIndicator queryParams = new PreMuCustomIndicator();
                queryParams.setCompanyType("1");
                queryParams.setYear(year);
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuCustomIndicatorService.removeData(queryParams, deptCode);
            } else if ("08".equals(deptCode)) {
                //规上企业自定义指标
                PreMuCustomIndicator queryParams = new PreMuCustomIndicator();
                queryParams.setCompanyType("2");
                queryParams.setYear(year);
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuCustomIndicatorService.removeData(queryParams, deptCode);
            } else if ("waterBureau".equals(deptCode)) {
                //删除水利局
                PreMuImportShuili queryParams = new PreMuImportShuili();
                queryParams.setYear(year);
                queryParams.setCompanyType("1");
                queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                preMuImportShuiliService.removeData(queryParams, deptCode);
            }
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            String requestURI = request.getRequestURI();
            SysOperError sysOperError = new SysOperError();
            sysOperError.setBaseId(IdUtil.simpleUUID());
            sysOperError.setBaseCreateTime(new Date());
            sysOperError.setErrorMsg(e.getMessage());
            sysOperError.setUrlAddress(requestURI);
            sysOperError.setOperId(SecurityUtils.getUserId());
            sysOperErrorMapper.saveErrorInfo(sysOperError);
            e.printStackTrace();
            return AjaxResult.error("删除失败");
        }

    }


    /**
     * <p>
     * 删除已汇入评价数据
     * </p>
     *
     * @param preMuImportLog
     * @return
     * @throws Exception
     */
    @RequiresPermissions("operation:pre_mu_import_log:removemc")
    @PostMapping("/removeMcData")
    public AjaxResult removeMcData(@RequestBody PreMuImportLog preMuImportLog) throws Exception {
        preMuImportLog.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        preMuImportLogService.removeCollectData(preMuImportLog);
        return AjaxResult.success();
    }

    /**
     * 导出导入模版
     *
     * @param year
     * @param deptCode
     * @param companyType
     * @param resp
     * @throws IOException
     */
    @PostMapping("/downloadTemplate")
    @RequiresPermissions("operation:pre_mu_import_log:downloadTemplate")
    public void downloadTemplate(String year, String deptCode, String companyType, HttpServletResponse resp) throws IOException {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        if (StringUtils.isBlank(year)) {
            LocalDate localDate = LocalDate.now();
            year = String.valueOf(localDate.getYear() - 1);
        }
        String fileName = "";
        String numType = "1";
        if ("01".equals(deptCode)) {
            companyType = "1";
            fileName = "规上企业-统计局导入数据模板.xlsx";
        } else if ("02".equals(deptCode)) {
            companyType = "1";
            fileName = "规上企业-生态环境局导入数据模板.xlsx";
        } else if ("03".equals(deptCode)) {
            companyType = "1";
            fileName = "规上企业-自然资源和规划局导入数据模板.xlsx";
        } else if ("04".equals(deptCode)) {
            companyType = "1";
            fileName = "规上企业-税务局导入数据模板.xlsx";
        } else if ("05".equals(deptCode)) {
            companyType = "1";
            fileName = "规上企业-人力资源和社会保障局导入数据模板.xlsx";
        } else if ("06".equals(deptCode)) {
            companyType = "2";
            fileName = "规下企业-统计局导入数据模板.xlsx";
        } else if ("07".equals(deptCode)) {
            companyType = "2";
            fileName = "规下企业-自然资源和规划局导入数据模板.xlsx";
        } else if ("09".equals(deptCode)) {
            companyType = "2";
            fileName = "规下企业-税务局导入数据模板.xlsx";
        } else if ("evaluationUpper".equals(deptCode)) {
            companyType = "1";
            fileName = "评价结果导入模板.xlsx";
        } else if ("evaluationlower".equals(deptCode)) {
            companyType = "2";
            fileName = "评价结果导入模板.xlsx";
        } else if ("notContestant_down".equals(deptCode) || "notContestant".equals(deptCode)) {
            numType = "2";
            fileName = "不参评企业基础数据导入（规上规下都可用）.xlsx";
        } else if ("waterBureau".equals(deptCode)) {
            fileName = "规上企业-水利局导入数据模板（试点县区）.xlsx";
        }

        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        if ("addupper".equals(deptCode) || "addlower".equals(deptCode) || "substractupper".equals(deptCode) || "substraclower".equals(deptCode)) {
            PreMuAddSubstractItem paramns = new PreMuAddSubstractItem();
            paramns.setCounty(sysUser.getDistrict());
            if ("addupper".equals(deptCode)) {
                fileName = "规上企业-加分项导入数据模板" + date + ".xlsx";
                paramns.setCompanyType("1");
                paramns.setItemType("1");
            } else if ("substractupper".equals(deptCode)) {
                fileName = "规上企业-减分项导入数据模板" + date + ".xlsx";
                paramns.setCompanyType("1");
                paramns.setItemType("2");
            } else if ("addlower".equals(deptCode)) {
                fileName = "规下企业-加分项导入数据模板" + date + ".xlsx";
                paramns.setCompanyType("2");
                paramns.setItemType("1");
            } else if ("substraclower".equals(deptCode)) {
                fileName = "规下企业-减分项导入数据模板" + date + ".xlsx";
                paramns.setCompanyType("2");
                paramns.setItemType("2");
            }
            Workbook wb = preMuAddSubstractItemService.createTemplateWb(paramns);
            resp.setHeader("content-type", "application/octet-stream");
            resp.setContentType("application/octet-stream");
            if (StringUtils.isBlank(fileName)) {
                fileName = UUID.randomUUID().toString().replace("-", "") + ".xlsx";
            }
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                os = resp.getOutputStream();
                if (wb != null) {
                    wb.write(os);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if ("custom".equals(deptCode) || "08".equals(deptCode)) {
            PreMuCustomIndicator paramMap = new PreMuCustomIndicator();
            if ("custom".equals(deptCode)) {
                fileName = "规上企业-自定义指标导入数据模板" + date + ".xlsx";
                paramMap.setCounty(sysUser.getDistrict());
                paramMap.setCompanyType("1");
            } else if ("08".equals(deptCode)) {
                fileName = "规下企业-自定义指标导入数据模板" + date + ".xlsx";
                paramMap.setCounty(sysUser.getDistrict());
                paramMap.setCompanyType("2");
            }

            Workbook wb = preMuCustomIndicatorService.createTemplateWb(paramMap);
            resp.setHeader("content-type", "application/octet-stream");
            resp.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            if (StringUtils.isBlank(fileName)) {
                fileName = UUID.randomUUID().toString().replace("-", "") + ".xlsx";
            }
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                os = resp.getOutputStream();
                if (wb != null) {
                    wb.write(os);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else if ("vetoupper".equals(deptCode) || "vetolower".equals(deptCode)) {
            PreMuReject paramMap = new PreMuReject();
            if ("vetoupper".equals(deptCode)) {
//                paramMap.put("year", LocalDate.now().getYear() - 1);
                paramMap.setYears(String.valueOf(LocalDate.now().getYear() - 1));
                fileName = "规上企业-否决项数据模板.xlsx";
//                paramMap.put("companyType", "1");
                paramMap.setEnterType("1");
                paramMap.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
//                paramMap.put("fileName", "规上企业-否决项数据模板.xlsx");
            } else if ("vetolower".equals(deptCode)) {
                paramMap.setYears(String.valueOf(LocalDate.now().getYear() - 1));
                fileName = "规下企业-否决项数据模板.xlsx";
                paramMap.setEnterType("2");
                paramMap.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
//                paramMap.put("fileName", "规下企业-否决项数据模板.xlsx");
            }
            Workbook wb = preMuRejectService.createTemplateWb(paramMap);

            resp.setHeader("content-type", "application/octet-stream");
            resp.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            if (StringUtils.isBlank(fileName)) {
                fileName = UUID.randomUUID().toString().replace("-", "") + ".xlsx";
            }
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                os = resp.getOutputStream();
                if (wb != null) {
                    wb.write(os);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            String filePath = fileMap.get(fileName);
            downloadDfsFileWithData(resp, filePath, fileName, companyType, numType, year);
        }
    }

    private void downloadDfsFileWithData(HttpServletResponse resp, String filePath, String fileName, String companyType, String numType, String year) throws IOException {
        File file = FileUtil.file(fileMap.get(fileName));
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String downFileName = fileName.replace(".xlsx", "");
        downFileName = downFileName + date + ".xlsx";
        PreMuCompanyInfo queryParams = new PreMuCompanyInfo();
        queryParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        queryParams.setCompanyType(companyType);
        queryParams.setNum(numType);
        queryParams.setYear(year);
        if (file != null) {
            InputStream is = new FileInputStream(file);
            Workbook wb = preMuImportLogService.writeCompanyInfo(queryParams, is);
            // 配置文件下载
            resp.setHeader("content-type", "application/octet-stream");
            resp.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(downFileName, "UTF-8"));
            // 实现文件下载
            OutputStream out = resp.getOutputStream();
            wb.write(out);
            wb.close();
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * <p>
     * 一键汇入
     * </p>
     *
     * @param params year:年份;companyType:企业类型
     * @return 结果
     */
    @RequiresPermissions("operation:pre_mu_import_log:onClickHuiZhong")
    @PostMapping("/onClickHuiZhong")
    public AjaxResult onClickHuiZhong(@RequestBody Map<String, String> params) {

        String companyType = null, year = null;
        if (StringUtils.isBlank(companyType = params.get("companyType")) || StringUtils.isBlank(year = params.get("year"))) {
            return AjaxResult.warn("请选择企业类型或者年份");
        }

        //获取用户信息
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        //填充用户的区县
        params.put("county", sysUser.getDistrict());

        //查询导入数据的记录 pre_mu_import_log表
        PreMuImportLog preMuImportLog = new PreMuImportLog();
        preMuImportLog.setYear(year);
        preMuImportLog.setCounty(params.get("county"));
        List<PreMuImportLog> preMuImportLogs = preMuImportLogService.selectPreMuImportLogList(preMuImportLog);

        //查询所有部门的字典项
        List<SysDictData> importDeptTypeArgs = DictUtils.getDictCache("import_dept_type");
        if (importDeptTypeArgs == null || importDeptTypeArgs.isEmpty()) {
            return AjaxResult.warn("没有找到导入部门相关数据");
        }

        List<String> collect = preMuImportLogs.stream().map(PreMuImportLog::getDeptCode).collect(Collectors.toList());
        //添加查询指标的代码
        if (collect.contains("evaluationlower") || collect.contains("evaluationUpper")) {
            collect.remove("evaluationlower");
            collect.remove("evaluationUpper");
            collect.remove("notContestant");
            collect.remove("notContestant_down");
            if (collect.size() > 0) {
                return AjaxResult.warn("导入了评价结果数据，无须导入其它部门的数据 ");
            }
        } else {
            PreMuIndexWeightMain indexWeightMainParams = new PreMuIndexWeightMain();
            indexWeightMainParams.setCounty(params.get("county"));
            indexWeightMainParams.setCompanyType(companyType);
            indexWeightMainParams.setYear(year);
            //PreMuIndexWeightMain preMuIndexWeightMain = preMuIndexWeightMainMapper.selectOne(indexWeightMainParams);
            List<PreMuIndexWeightMain> preMuIndexWeightMainList = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainListNew(indexWeightMainParams);

            if (preMuIndexWeightMainList == null ||  preMuIndexWeightMainList.size()==0) {
                return AjaxResult.warn("指标权重为空！请设置指标权重");
            }

            //List<PreMuIndexWeightSub> preMuIndexWeightSubList = preMuIndexWeightMain.getPreMuIndexWeightSubList();
            //        List<PreMuIndexWeightSub> waterIndicators = new ArrayList<>();
            //        if(preMuIndexWeightSubList != null && !preMuIndexWeightSubList.isEmpty()){
            //            waterIndicators = preMuIndexWeightSubList.stream().filter(item -> item.getIndexName().equals("单位水耗销售收入")).collect(Collectors.toList());
            //        }
            for (SysDictData deptType : importDeptTypeArgs) {

                //只有规上企业存在试点区县
                if (StringUtils.equals(companyType, "1")) {
//                if (deptType.getDictValue().equals("waterBureau")
//                        && (waterIndicators.get(0) == null || waterIndicators.get(0).getIndexValue().equals("1")|| waterIndicators.get(0).getIndexValue().equals("2"))) {
//                    continue;
//                }

//                if (deptType.getDictValue().equals("waterBureau")) {
//                    if(waterIndicators.isEmpty() || waterIndicators.get(0).getIndexValue().equals("1")|| waterIndicators.get(0).getIndexValue().equals("2")){
//                        continue;
//                    }
//                }

                    if (deptType.getDictValue().equals("waterBureau")) {
                        if (preMuIndexWeightMainList == null || preMuIndexWeightMainList.size()==0) {
                            continue;
                        }
                        if(preMuIndexWeightMainList != null && preMuIndexWeightMainList.size()>0) {
//                            for(PreMuIndexWeightMain preMuIndexWeightMain:preMuIndexWeightMainList){
//                                if(StringUtils.equals(preMuIndexWeightMain.getWaterConsumption(), "0")){
//                                    continue outerLoop;
//                                }
//                            }
                            long count = preMuIndexWeightMainList.stream().filter(f -> "1".equals(f.getWaterConsumption())).count();
                            if(count <= 0){
                                continue;
                            }


                        }
                    }



                }
                if ("1".equals(companyType)) {
                    if ("06".equals(deptType.getDictValue()) || "07".equals(deptType.getDictValue()) || "08".equals(deptType.getDictValue()) || "09".equals(deptType.getDictValue()) || "vetolower".equals(deptType.getDictValue()) || "addlower".equals(deptType.getDictValue()) || "substraclower".equals(deptType.getDictValue()) || "shuishou".equals(deptType.getDictValue())) {
                        continue;
                    }
                } else {
                    if (!"06".equals(deptType.getDictValue()) && !"07".equals(deptType.getDictValue()) && !"08".equals(deptType.getDictValue()) && !"09".equals(deptType.getDictValue()) && !"vetolower".equals(deptType.getDictValue()) && !"addlower".equals(deptType.getDictValue()) && !"substraclower".equals(deptType.getDictValue())) {//&& !"shuishou".equals(deptType.getValue())) {
                        continue;
                    }
                }

                boolean flag = true;
                if (!"custom".equals(deptType.getDictValue()) && !"08".equals(deptType.getDictValue())) {
                    for (int i = 0; i < preMuImportLogs.size(); i++) {
                        PreMuImportLog logDO = preMuImportLogs.get(i);
                        if (deptType.getDictValue().equals(logDO.getDeptCode()) || deptType.getDictValue().equals("addupper")
                                || deptType.getDictValue().equals("addlower") || deptType.getDictValue().equals("substraclower")
                                || deptType.getDictValue().equals("vetolower") || deptType.getDictValue().equals("vetoupper")
                                || deptType.getDictValue().equals("substractupper")
                                || deptType.getDictValue().equals("evaluationlower") || "evaluationlower".equals(logDO.getDeptCode())
                                || deptType.getDictValue().equals("evaluationUpper") || "evaluationUpper".equals(logDO.getDeptCode())
                                || "notContestant".equals(logDO.getDeptCode()) || "notContestant_down".equals(logDO.getDeptCode())
                                || "notContestant".equals(deptType.getDictValue()) || "notContestant_down".equals(deptType.getDictValue())) {
                            flag = false;
                            break;
                        }
                    }
//                if (flag && !deptType.getDictValue().equals("notContestant_down") && !deptType.getDictValue().equals("notContestant")) {
//                    //return R.error("本年度 "+ deptType.getName() + "尚未导入，请先导入该部门数据！ ");
//                    params.put("sign", deptType.getDictLabel());
//                }

                    if (flag) {
                        //return R.error("本年度 "+ deptType.getName() + "尚未导入，请先导入该部门数据！ ");
                        params.put("sign", deptType.getDictLabel());
                    }
                }
            }
        }
        return preMuImportLogService.collectData(params);
    }
}
